(*
  Copyright (c) 2009 Barry Schwartz

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*)

open Job
open Pycaml

(*-----------------------------------------------------------------------*)
(* hooks for loaded modules *)

let hook_parse_state = ref []
let hook_initialise = ref []
let register_parse_state_hook h = hook_parse_state := h :: !hook_parse_state
let register_init_hook h = hook_initialise := h :: !hook_initialise
let call_parse_state_hooks ps = List.iter (fun h -> h ps) !hook_parse_state
let call_init_hooks () = List.iter (fun h -> h ()) !hook_initialise
  
(*-----------------------------------------------------------------------*)
(* routines to start ant *)

let initialise () =
  let _ = Fonts.initialise_font_table () in
    call_init_hooks ()
  
let parse_document ps =
  Primitives.initialise ps;
  call_parse_state_hooks ps;
  ParseState.run_parser ps `Preamble
  
let parse_file job name =
  let ps = ParseState.create job in
    UCStream.include_file ps.ParseState.input_stream name;
    (parse_document ps, ps)
  
let parse_string job str =
  let ps = ParseState.create job in
    UCStream.insert_string ps.ParseState.input_stream str;
    (parse_document ps, ps)

(*-----------------------------------------------------------------------*)

let py_initialize_run =
  python_interfaced_function
    [| |]
    (fun _py_args -> initialise (); pynone ())

let py_call_parse_state_hooks =
  python_interfaced_function
    [| CamlpillSubtype "parse_state" |]
    begin
      fun py_args ->
        let ps = ParseState.unpythonize_parse_state py_args.(0) in
          call_parse_state_hooks ps;
          pynone ();
    end

let _ =
  register_for_python
    [|
      ("initialize_run", py_initialize_run);
      ("call_parse_state_hooks", py_call_parse_state_hooks);
    |]

(*-----------------------------------------------------------------------*)
